/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ClientServer;

import GUI.Login;
import GUI.MainScreen;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.BindException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;

/**
 *
 * @author Van Cong
 */
public class Server {

    private ServerSocket serverSocket;
    private MainScreen mainGUI;
    static Pattern macpt = null;
    public static String ip;

    public static String getMac(String ip) {
        // Find OS and set command according to OS
        String OS = System.getProperty("os.name").toLowerCase();
        String[] cmd;
        if (OS.contains("win")) {
            // Windows
            macpt = Pattern.compile("[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+");
            String[] a = {"arp", "-a", ip};
            cmd = a;
        } else {
            // Mac OS X, Linux
            macpt = Pattern.compile("[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+");
            String[] a = {"arp", ip};
            cmd = a;
        }

        try {
            // Run command
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();
            // read output with BufferedReader
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            String line = reader.readLine();

            // Loop trough lines
            while (line != null) {
                Matcher m = macpt.matcher(line);

                // when Matcher finds a Line then return it as result
                if (m.find()) {
                    System.out.println("Found");
                    System.out.println("MAC: " + m.group(0));
                    return m.group(0);
                }

                line = reader.readLine();
            }

        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // Return empty string if no MAC is found
        return "";
    }

    public Server(MainScreen main) {
        mainGUI = main;
        try {
            serverSocket = new ServerSocket(2014);
            System.out.println("Khởi động máy chủ thành công!");
            ip = serverSocket.getInetAddress().getLocalHost().getHostAddress();
            new AcceptConect();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Phần mềm đã được mở.", "Mở chương trình nhiều lần", JOptionPane.OK_OPTION);
            System.exit(0);
        }            
    }

    public void closeConect() {
        try {
            serverSocket.close();
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    class AcceptConect extends Thread {

        public AcceptConect() {
            start();
        }

        public void run() {
            while (true) {
                try {
                    Socket socket = serverSocket.accept();
                    String mac = getMac(socket.getInetAddress().getHostAddress());
                    String query = "SELECT * FROM COMPUTER";
                    boolean newMac = true;
                    int id = 0;
                    ResultSet resultSet = Login.dtConnect.retriveData(query);
                    try {
                        while (resultSet.next()) {
                            if (resultSet.getString(2).equals(mac)) {
                                id = Integer.parseInt(resultSet.getString(1));
                                newMac = false;
                                break;
                            }
                        }
                    } catch (SQLException ex) {
                    }
                    if (newMac) {
                        query = "SELECT COUNT(NAMECOM) FROM COMPUTER";
                        resultSet = Login.dtConnect.retriveData(query);
                        try {
                            resultSet.next();
                            id = resultSet.getInt(1) + 1;
                        } catch (SQLException ex) {
                            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        query = "insert into COMPUTER (NAMECOM, MACADDRESS) value (" + id + ", '" + mac + "')";
                        Login.dtConnect.updateData(query);
                        mainGUI.newComputer(socket, id);
                    } else {
                        mainGUI.setComputer(socket, id);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    class InputServer extends Thread {

        private DataInputStream dataIn;
        private Socket socket;

        public InputServer(Socket socket, DataInputStream dataInput) {
            this.socket = socket;
            dataIn = dataInput;
            start();
        }

        public void run() {
            while (true) {
                try {
                    mainGUI.setAction(dataIn.readUTF());
                } catch (IOException ex) {
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}
